package com.nf.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.nf.dao.StudentDao;
import com.nf.dao.StudentsDaoImpl;
import com.nf.entity.Students;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/QueryStudent")
public class QueryServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("进入查询");
        //设置响应编码
        response.setContentType("application/json;charset=utf-8");
        //调用dao操作数据库查询
        StudentDao dao = new StudentsDaoImpl();
        List<Students> studentsList = new ArrayList<Students>();
        //比较为空就查询全部，否则根据ID查询
        if(request.getParameter("id").equals("")){
            studentsList = dao.queryAll();
        }else {
            //获取客户端数据
            int id = Integer.parseInt(request.getParameter("id"));
            Students students = dao.query(id);
            if(students==null){
                studentsList = dao.queryAll();
            }else {
                studentsList.add(students);
                System.out.println(students);
            }
        }
        //使用jackson将对象转换为json打印回客户端
        ObjectMapper objectMapper = new ObjectMapper();
        //定义一个模板设置日期格式
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));

        response.getWriter().print(objectMapper.writeValueAsString(studentsList));
    }
}
